const { ipcRenderer } = require('electron')

// 移除 Store 相关代码，因为设置功能已经在主进程中处理
const noteId = Date.now().toString()

// 加载保存的内容
function loadNoteContent() {
    const noteContent = localStorage.getItem(`noteContent_${noteId}`) || ''
    const noteTitle = localStorage.getItem(`noteTitle_${noteId}`) || ''
    document.getElementById('noteContent').value = noteContent
    document.getElementById('noteTitle').value = noteTitle
    document.title = noteTitle || '便签'
}

// 自动保存内容
document.getElementById('noteContent').addEventListener('input', (e) => {
    const content = e.target.value
    localStorage.setItem(`noteContent_${noteId}`, content)
})

// 自动保存标题
document.getElementById('noteTitle').addEventListener('input', (e) => {
    const title = e.target.value
    localStorage.setItem(`noteTitle_${noteId}`, title)
    document.title = title || '便签'
})

// 监听设置更新
ipcRenderer.on('update-settings', (event, settings) => {
    if (settings.fontSize) {
        document.getElementById('noteContent').style.fontSize = `${settings.fontSize}px`
    }
})

// 添加关闭按钮功能
document.getElementById('closeButton').addEventListener('click', () => {
    console.log('关闭按钮被点击')
    // 保存内容
    const content = document.getElementById('noteContent').value
    const title = document.getElementById('noteTitle').value
    localStorage.setItem(`noteContent_${noteId}`, content)
    localStorage.setItem(`noteTitle_${noteId}`, title)
    
    // 发送关闭信号给主进程
    ipcRenderer.send('close-note')
    console.log('已发送关闭信号')
})

// 防止关闭按钮触发拖动
document.getElementById('closeButton').addEventListener('mousedown', (e) => {
    e.stopPropagation()
})

// 确保点击关闭按钮时不会触发拖动
document.querySelector('.title-bar').addEventListener('mousedown', (e) => {
    if (e.target === document.getElementById('closeButton') || e.target.closest('.close-button')) {
        e.preventDefault()
        e.stopPropagation()
    }
})

// 添加调试日志
console.log('renderer.js 已加载')

// 初始化
loadNoteContent() 